import axios from 'axios';
import { message } from "ant-design-vue";
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'
// 创建axios实例
const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: import.meta.env.VITE_APP_BASE_URL,
    // 超时
    timeout: 10000
});

// request拦截器
service.interceptors.request.use(
    (config) => {
        return config;
    },
    (error) => {
        Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    response => {
        return response.data;
    },
    error => {
        const response = error.response;
        let msg
        if (response == null) {
            msg = '网络连接失败 ~'

            setTimeout(() => {
                message.warning(msg);
            }, 100)
            return Promise.reject(error)
        }
        else if (response.status === 404) {
            msg = '请求资源不存在 ~'

            setTimeout(() => {
                message.warning(msg)
            }, 100)
            return Promise.reject(error)
        }
        else if (response.status === 500) {
            msg = '系统繁忙，请稍后再试 ~'

            setTimeout(() => {
                message.warning(msg)
            }, 100)
            return Promise.reject(error)
        }
        if (response.data.message != null) {
            msg = response.data.message

            setTimeout(() => {
                message.warning(msg)
            }, 100)
            return Promise.reject(error)
        }

        setTimeout(() => {
            message.error('发生未知错误')
        }, 100)
        return Promise.reject(error)
    }
);

export default service;
